import React, { memo, useState } from "react"
import { Col, Row, Button, Form, Input, message, notification } from "antd"
import {
	saveTokenAction,
	saveUserInfoAction,
	saveDynamicRouteListAction,
} from "@/store/modules/user"
import { reqLogIn, reqUserInfo } from "@/api/user"
import "./index.less"
import { shallowEqual, useDispatch } from "react-redux"
import { useNavigate } from "react-router-dom"
import { dynamicRoutes } from "@/router/routers"
import { getTimeRegion, filterRoutes } from "@/utils"
import { useAppSelector } from "@/store"
const cloneDeep = require("lodash/cloneDeep")
type FieldType = {
	username?: string
	password?: string
}
const Login: React.FC = () => {
	const { dynamicRouteList } = useAppSelector(
		(state) => ({
			dynamicRouteList: state.userStore.dynamicRouteList,
		}),
		shallowEqual,
	)
	const dispatch = useDispatch()
	const navigate = useNavigate()
	const [loading, setLoading] = useState<boolean>(false)
	const [form] = Form.useForm()
	const onFinish = (values: any) => {
		console.log("Success:", values)
		setLoading(true)
		try {
			reqLogIn(values).then((res) => {
				if (res.code === 200) {
					console.log("token", res.data)
					dispatch(saveTokenAction(res.data))
					dynamicRouteList === "[]" && getUserInfo()
				} else {
					message.error({
						content: res?.message || "登录失败！！！",
					})
					throw Error(res?.message)
				}
			})
		} catch (error) {
			message.error({
				content: "登录失败！！！",
			})
			console.log(error)
		} finally {
			setLoading(false)
		}
	}

	const getUserInfo = () => {
		reqUserInfo()
			.then((res) => {
				if (res.code === 200) {
					console.log("userinfo", res.data)
					dispatch(saveUserInfoAction(res.data))
					notification.success({
						message: "登录成功",
						description: (
							<span>
								尊敬的用户：
								{<span style={{ color: "red" }}>{res.data?.name}</span>}，欢迎
								{getTimeRegion()}回来！！！
							</span>
						),
						duration: 6,
					})
					const routes = filterRoutes(
						cloneDeep(dynamicRoutes),
						res?.data?.routes as string[],
					)
					console.log(routes)

					dispatch(saveDynamicRouteListAction(JSON.stringify(routes)))
					navigate("/home")
				}
			})
			.catch((error) => {
				console.log(error)
			})
	}

	const onFinishFailed = (errorInfo: any) => {
		console.log("Failed:", errorInfo)
	}
	return (
		<div className="login-container">
			<Row>
				<Col span={12}></Col>
				<Col className="login_form" span={12}>
					<div className="card">
						<h1>Hello</h1>
						<p>欢迎登录！！！</p>
						<Form
							form={form}
							name="login"
							initialValues={{ username: "admin", password: "atguigu123" }}
							labelCol={{ span: 4 }}
							wrapperCol={{ span: 20 }}
							onFinish={onFinish}
							onFinishFailed={onFinishFailed}
							autoComplete="off"
						>
							<Form.Item<FieldType>
								label="Username"
								name="username"
								rules={[
									{
										required: true,
										message: "请输入用户名",
										validateTrigger: "blur",
									},
									{ min: 5, message: "用户名至少5位", validateTrigger: "blur" },
								]}
							>
								<Input />
							</Form.Item>

							<Form.Item<FieldType>
								label="Password"
								name="password"
								rules={[
									{
										required: true,
										message: "请输入密码",
										validateTrigger: "blur",
									},
									{
										min: 6,
										max: 22,
										message: "密码6-22位",
										validateTrigger: "blur",
									},
								]}
							>
								<Input.Password />
							</Form.Item>

							<Form.Item wrapperCol={{ offset: 4, span: 20 }}>
								<Button
									loading={loading}
									type="primary"
									className="login_btn"
									htmlType="submit"
								>
									登录
								</Button>
							</Form.Item>
						</Form>
					</div>
				</Col>
			</Row>
		</div>
	)
}
export default memo(Login)
